/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
 package com.wealth.merchant.web.controller;


import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wealth.commodity.entity.GoodsPic;
import com.wealth.merchant.entity.BusinessDistrict;
import com.wealth.merchant.entity.Market;
import com.wealth.merchant.entity.Merchant;
import com.wealth.merchant.entity.MerchantPic;
import com.wealth.merchant.service.IBusinessDistrictService;
import com.wealth.merchant.service.IMarketService;
import com.wealth.merchant.service.IMerchantService;
import com.wealth.system.entity.User;
import com.wealth.system.service.IUserService;
import com.wealth.system.service.ShiroUser;
import com.wealth.system.web.controller.BaseController;

import iaas.annotation.Log;
import iaas.enums.StatusEnum;
import iaas.utils.RedirectMessage;
import iaas.web.JqGridRequest;
import iaas.web.JqGridResponse;
import iaas.web.JqGridUtil;

/**
 * @author chan
 * @version 1.0
 * @since 1.0
 */
 
@Controller
@RequestMapping(value="/manage/merchant/merchant")
public class MerchantController extends BaseController{

	Logger logger = Logger.getLogger(MerchantController.class);
	
	@Autowired
	private IMerchantService merchantService;
	@Autowired
	private IBusinessDistrictService businessDistrictService;
	@Autowired
	private IMarketService marketService;
	@Autowired
	private IUserService userService;
	
	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Classify对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void init(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) {
		try{
			if (id != -1) {
				Merchant merchant = merchantService.get(id);
				model.addAttribute("merchant", merchant);
			}
		}catch(Exception e){
			logger.error("初始化错误", e);
		}
	}
	
	/**
	 * 列表
	 */
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String list(Model model){
		try{
			List<BusinessDistrict> businessDistrictList = businessDistrictService.findByPropertyName("status", StatusEnum.NORMAL.getValue(), BusinessDistrict.class);
			model.addAttribute("businessDistrictList", businessDistrictList);
			
			List<Market> marketList = marketService.findByPropertyName("status", StatusEnum.NORMAL.getValue(), Market.class);
			model.addAttribute("marketList", marketList);
			
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			model.addAttribute("corpid", corpid);
			return "merchant/merchant/list";
		}catch(Exception e){
			logger.error("列表页面错误", e);
			return "system/500";
		}
	}
	
	
	/**
	 * 列表ajax查询数据
	 */
	@RequestMapping(value="/list",method = RequestMethod.POST)
	@ResponseBody
	public JqGridResponse getJson(Model model,JqGridRequest request) {
		try{

			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			
			Page<Merchant> page = merchantService.get(corpid, request,Merchant.class);
			
			return JqGridUtil.getJqGrirdResponse(page);
		}catch(Exception e){
			logger.error("列表错误！", e);
			return null;
		}
	}
	
	
	/**
	 * 详情
	 */
	@RequestMapping(value="/{id}",method = RequestMethod.GET)
	public String infoForm(Model model,@PathVariable("id") Long id){
		try{
			Merchant merchant = merchantService.get(id);
			model.addAttribute("merchant", merchant);
			return "merchant/merchant/info";
		}catch(Exception e){
			logger.error("详情页面错误,id="+id, e);
			return "system/500";
		}
	}
	
	
	/**
	 * 创建页面
	 */
	@RequestMapping(value="/create",method = RequestMethod.GET)
	public String createForm(Model model,String item){
		try {
			List<BusinessDistrict> businessDistrictList = businessDistrictService.getByParentIdIsNullAndStatus(StatusEnum.NORMAL.getValue());
			model.addAttribute("businessDistrictList", businessDistrictList);
			
			List<Market> marketList = marketService.findByPropertyName("status", StatusEnum.NORMAL.getValue(), Market.class);
			model.addAttribute("marketList", marketList);
			
			return "merchant/merchant/create";
		} catch (Exception e) {
			logger.error("创建页面错误", e);
			return "system/500";	
		}
	}
	
	
	
	/**
	 * 创建限填超页面
	 */
	@RequestMapping(value="/creatextc",method = RequestMethod.GET)
	public String createFormXtc(Model model,String item){
		try {
			List<BusinessDistrict> businessDistrictList = businessDistrictService.getByParentIdIsNullAndStatus(StatusEnum.NORMAL.getValue());
			model.addAttribute("businessDistrictList", businessDistrictList);
			
			List<Market> marketList = marketService.findByPropertyName("status", StatusEnum.NORMAL.getValue(), Market.class);
			model.addAttribute("marketList", marketList);
			
			return "merchant/merchant/creatextc";
		} catch (Exception e) {
			logger.error("创建页面错误", e);
			return "system/500";	
		}
	}
		
		
	
	/**
	 * 加载子节点
	 */
	@RequestMapping(value="/ajaxChild",method = RequestMethod.POST)
	@ResponseBody
	public List<BusinessDistrict> ajaxChild(@RequestParam Long pid){
		try{
			List<BusinessDistrict> businessDistrictLists = businessDistrictService.getByParentIdAndStatus(pid, StatusEnum.NORMAL.getValue());
			return businessDistrictLists;
		}catch(Exception e){
			logger.error("修改排序错误", e);
			return null;
		}
	}
	
	
	
	/**
	 * 创建
	 */
	@RequestMapping(value="/create",method = RequestMethod.POST)
	public String create(Model model,Merchant merchant,String username,String password,RedirectAttributes redirectAttributes,HttpServletRequest request){
		try {
			
			String[] picurls = request.getParameterValues("PicList");
			if(picurls!=null){
				for (String str : picurls) {
					MerchantPic pic = new MerchantPic();
					pic.setPicurl(str);
					merchant.getMerchantPicList().add(pic);
				}
			}
			//商户管理员
			username = username.trim();
			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			merchantService.saveMerchant(merchant, user);

			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("创建成功"));
			return "redirect:/manage/merchant/merchant/list";
		} catch (Exception e) {
			logger.error("创建错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 编辑页面
	 */
	@RequestMapping(value="/update/{id}",method = RequestMethod.GET)
	public String setUpdateForm(Model model,@PathVariable("id") Long id){
		try{
			//父节点列表
			List<BusinessDistrict> businessDistrictList = businessDistrictService.getByParentIdIsNullAndStatus(StatusEnum.NORMAL.getValue());
			model.addAttribute("businessDistrictList", businessDistrictList);
			
			List<Market> marketList = marketService.findByPropertyName("status", StatusEnum.NORMAL.getValue(), Market.class);
			model.addAttribute("marketList", marketList);
		
			Merchant merchant = merchantService.get(id);
			model.addAttribute("merchant", merchant);
			
			Long userid = merchant.getUserList().get(0).getId();
			model.addAttribute("userid", userid);
			
			//子节点列表
			Long pid = merchant.getDistrict().getParent().getId();
			List<BusinessDistrict> businessDistrictLists = businessDistrictService.getByParentIdAndStatus(pid, StatusEnum.NORMAL.getValue());
			model.addAttribute("businessDistrictLists", businessDistrictLists);
			return "merchant/merchant/update";
		}catch(Exception e){
			logger.error("编辑页面错误,id="+id, e);
			return "system/500";
		}
	}
	
	
	/**
	 * 限天超编辑页面
	 */
	@RequestMapping(value="/updatextc/{id}",method = RequestMethod.GET)
	public String setUpdateFormxfc(Model model,@PathVariable("id") Long id){
		try{
			//父节点列表
			List<BusinessDistrict> businessDistrictList = businessDistrictService.getByParentIdIsNullAndStatus(StatusEnum.NORMAL.getValue());
			model.addAttribute("businessDistrictList", businessDistrictList);
			
			List<Market> marketList = marketService.findByPropertyName("status", StatusEnum.NORMAL.getValue(), Market.class);
			model.addAttribute("marketList", marketList);
		
			Merchant merchant = merchantService.get(id);
			model.addAttribute("merchant", merchant);
			
			Long userid = merchant.getUserList().get(0).getId();
			model.addAttribute("userid", userid);
			
			//子节点列表
			Long pid = merchant.getDistrict().getParent().getId();
			List<BusinessDistrict> businessDistrictLists = businessDistrictService.getByParentIdAndStatus(pid, StatusEnum.NORMAL.getValue());
			model.addAttribute("businessDistrictLists", businessDistrictLists);
			return "merchant/merchant/updatextc";
		}catch(Exception e){
			logger.error("限天超编辑页面错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 修改信息
	 */
	@RequestMapping(value="/update/{id}",method = RequestMethod.POST)
	public String update(@PathVariable("id") Long id,@ModelAttribute("merchant") Merchant merchant,RedirectAttributes redirectAttributes,HttpServletRequest request){
		try{
			merchantService.clear();
			
			String[] picurls = request.getParameterValues("PicList");
			if(picurls!=null){
				
				for (String str : picurls) {
					MerchantPic pic = new MerchantPic();
					pic.setPicurl(str);
					merchant.getMerchantPicList().add(pic);
				}
			}
			
			merchantService.updateMerchant(merchant);
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("编辑成功"));
			return "redirect:/manage/merchant/merchant/list";
		}catch(Exception e){
			logger.error("编辑错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 删除（逻辑删除）
	 */
	@RequestMapping(value="/delete/{id}",method = RequestMethod.GET)
	public String delete(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			merchantService.deleteLogical(id);
			List<User> users=merchantService.get(id).getUserList();
			if(users.size()>0){
				for (int i = 0; i < users.size(); i++) {
					User user=userService.get(users.get(i).getId());
					user.setStatus(StatusEnum.DELETE.getValue());
					userService.save(user);
				}
			}
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("删除成功"));
			return "redirect:/manage/merchant/merchant/list";
		}catch(Exception e){
			logger.error("删除错误,id="+id,e);
			return "system/500";
		}
	}
	
	/**
	 * 停用
	 */
	@RequestMapping(value="/disable/{id}",method = RequestMethod.GET)
	public String disable(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			
			merchantService.updateStatus(id, StatusEnum.STOP.getValue());
			
			List<User> users=merchantService.get(id).getUserList();
			if(users.size()>0){
				for (int i = 0; i < users.size(); i++) {
					User user=userService.get(users.get(i).getId());
					user.setStatus(StatusEnum.STOP.getValue());
					userService.save(user);
				}
			}
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipWarning("停用成功"));
			return "redirect:/manage/merchant/merchant/list";
		}catch(Exception e){
			logger.error("停用错误,id="+id,e);
			return "system/500";
		}
	}
	
	/**
	 * 启用
	 */
	@RequestMapping(value="/enable/{id}",method = RequestMethod.GET)
	public String enable(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			merchantService.updateStatus(id, StatusEnum.NORMAL.getValue());
			List<User> users=merchantService.get(id).getUserList();
			if(users.size()>0){
				for (int i = 0; i < users.size(); i++) {
					User user=userService.get(users.get(i).getId());
					user.setStatus(StatusEnum.NORMAL.getValue());
					userService.save(user);
				}
			}
			
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipWarning("启用成功"));
			return "redirect:/manage/merchant/merchant/list";
		}catch(Exception e){
			logger.error("启用错误,id="+id,e);
			return "system/500";
		}
	}
	
	/**
	 * 修改排序
	 */
	@RequestMapping(value="/update/seq",method = RequestMethod.POST)
	@ResponseBody
	public String updateSeq(HttpServletRequest request , @ModelAttribute("merchant") Merchant merchant){
		try{
			merchantService.save(merchant);
			return "success";
		}catch(Exception e){
			logger.error("修改排序错误", e);
			return "fail";
		}
	}
	
	/**
	 * 批量删除
	 * 2015-07-15 by chan
	 * ----------- 参数说明 ----------
	 * ids 商户ID
	 * 
	 */
	@RequestMapping(value="/batchDelete",method = RequestMethod.GET)
	public String batchDelete(@RequestParam String ids,RedirectAttributes redirectAttributes){
		try{
			String id[] = ids.split(",");
			for (String mid : id) {
				Long merchantId = Long.parseLong(mid);
				merchantService.deleteLogical(merchantId);
				List<User> users=merchantService.get(merchantId).getUserList();
				if(users.size()>0){
					for (int i = 0; i < users.size(); i++) {
						User user=userService.get(users.get(i).getId());
						user.setStatus(StatusEnum.DELETE.getValue());
						userService.save(user);
					}
				}
				}
			return "redirect:/manage/merchant/merchant/list";
		}catch(Exception e){
			logger.error("删除错误,ids="+ids,e);
			return "system/500"; 
		}
		
	}
	
	/**
	 * 导入页面
	 */
	@RequestMapping(value="/import",method = RequestMethod.GET)
	public String importForm(Model model){
		try {
			//市场
			List<Market> marketList = marketService.findByPropertyName("status", StatusEnum.NORMAL.getValue(), Market.class);
			model.addAttribute("marketList", marketList);
			//商圈
			List<BusinessDistrict> districtList = businessDistrictService.findByPropertyName("status", StatusEnum.NORMAL.getValue(), BusinessDistrict.class);
			model.addAttribute("districtList", districtList);
			
			return "merchant/merchant/import";
		} catch (Exception e) {
			logger.error("创建页面错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 导入商户
	 */
	@Log(method="导入商户")
	@RequestMapping(value="/import",method = RequestMethod.POST)
	public String importMerchant(DefaultMultipartHttpServletRequest request, 
			Model model,Long marketid,Long districtid,
			RedirectAttributes redirectAttributes){
		try {
			MultipartFile file = request.getFile("file");
			boolean flag = merchantService.importFile(file, marketid,districtid);
			if(flag){
				redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("导入成功"));
			}else{
				redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("导入失败"));
			}
			return "redirect:/manage/merchant/merchant/list";
		} catch (Exception e) {
			logger.error("创建错误", e);
			return "system/500";
		}
	}
}

